package com.example.data.factory.service.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.data.factory.common.Dto.LoginDto;
import com.example.data.factory.common.common.StringConstant;
import com.example.data.factory.common.result.R;
import com.example.data.factory.common.util.CommonUtil;
import com.example.data.factory.common.util.JwtUtil;
import com.example.data.factory.common.util.Md5Utils;
import com.example.data.factory.entity.entity.Personnel;
import com.example.data.factory.mapper.mapper.PersonnelMapper;
import com.example.data.factory.service.service.PersonnelService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class PersonnelServiceImpl extends ServiceImpl<PersonnelMapper, Personnel> implements PersonnelService {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private CommonUtil commonUtil;

    @Override
    public R<Personnel> serach(LoginDto loginDto) {
        //登录，首先应该根据账号拿到该信息，先判断数据是否存在，如果存在，就用表里的数据和输入的数据进行比对，如果相同就登录成功，如果不同就登录失败
        //根据账号进行查询
        Personnel one = this.getOne ( new LambdaQueryWrapper<Personnel> ().eq ( Personnel::getLoginAccount, loginDto.getLoginAccount () ) );
        if (Objects.isNull ( one )) {
            return R.Failed ( "该信息不存在" );
        }
        //进行密码比较
        if (!one.getPassword ().equals ( Md5Utils.hash ( loginDto.getPassword () ) )) {
            return R.Failed ( "密码错误" );
        }
        Map<String, String> map = new HashMap<> ();
        map.put ( "username", one.getPersonName () );
        map.put ( "account", one.getLoginAccount () );
        try {
            String token = jwtUtil.createToken ( map );
            return R.Success ( token );
        } catch (Exception e) {
            return R.Failed ( StringConstant.SYSTEMERROR );
        }
    }

    @Override
    public R getAccount(HttpServletRequest request) {
        try {
            // 使用工具类提取用户名
            String username = commonUtil.extractUsernameFromRequest ( request );

            // 返回成功结果
            return R.Success ( username );
        } catch (RuntimeException e) {
            // 捕获异常并返回失败结果
            return R.Failed ( e.getMessage () );
        }
    }
}

